package com.mrjoew.weekend.services.impl.shop;

import com.mrjoew.weekend.entities.dto.shop.GoodsDTO;
import com.mrjoew.weekend.entities.po.shop.GoodsPO;
import com.mrjoew.weekend.entities.vo.shop.GoodsVO;
import com.mrjoew.weekend.repositories.shop.GoodsRepository;
import com.mrjoew.weekend.services.shop.GoodsService;
import org.modelmapper.ModelMapper;
import org.springframework.data.domain.Example;
import org.springframework.data.domain.ExampleMatcher;
import org.springframework.data.domain.Page;
import org.springframework.data.domain.Pageable;
import org.springframework.stereotype.Service;

import javax.transaction.Transactional;
import java.util.List;

/**
 * @author Christopher Jones
 * @ClassName GoodsServiceImpl
 * @explain
 * @date 2020/11/5 0005 22:28
 */
@Service
@Transactional
public class GoodsServiceImpl implements GoodsService {

    private final GoodsRepository goodsRepository;

    public GoodsServiceImpl(GoodsRepository goodsRepository) {
        this.goodsRepository = goodsRepository;
    }

    @Override
    public GoodsPO save(GoodsPO goodsPO) {
        return goodsRepository.save(goodsPO);
    }

    @Override
    public List<GoodsPO> saveAll(List<GoodsPO> pos) {
        return goodsRepository.saveAll(pos);
    }

    @Override
    public Page<GoodsPO> list(GoodsDTO condition, Pageable pageable) {
        ExampleMatcher matcher = ExampleMatcher.matching().withMatcher("brand", ExampleMatcher.GenericPropertyMatchers.contains());
        GoodsPO po = new GoodsPO();
        po.setBrand(condition.getBrand());
        Example<GoodsPO> example = Example.of(po, matcher);
        return goodsRepository.findAll(example, pageable);
    }

    @Override
    public GoodsVO get(Integer id) {
        return goodsRepository.findById(id).map(goodsPO -> new ModelMapper().map(goodsPO, GoodsVO.class)).orElse(null);
    }
}
